package com.heima.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/*
全局过滤器，校验token是否有效
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {


    /**
     * 执行过滤的方法
     *
     * @param exchange 交换机，可以获取请求和响应对象
     * @param chain    过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //TODO

        //获取响应和请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求路径，判断是否在白名单
        //springMVC已经做过拦截了
        String requestPath = request.getURI().getPath();



        //判断请求头中是否带有token
        List<String> tokens = request.getHeaders().get("token");
        if (tokens.size() == 0 || CollUtil.isEmpty(tokens)) {
            //请求头中没有携带token
            //设置响应码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //解析token
        String token = tokens.get(0);
        try {
            Claims  claimsBody = AppJwtUtil.getClaimsBody(token);
            //验证是否过期，-1：有效，0：有效，1：过期，2：过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            if (i == 1 || i == 2) {
                //token过期，则返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            String userId = claimsBody.getId();
            //给响应设置用户信息
            request.mutate().header("user-info",userId);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            //8. 如果Token解析失败则响应401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    /**
     * 过滤的执行的优先级，返回值越小优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
